package pdamh.view.utils;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.InputMap;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;

public class JTablePDAMH extends JTable {

	private static final long serialVersionUID = 1L;
	
	private Map<String, TableCellEditor> mapCellEditors = new HashMap<String, TableCellEditor>();

	public JTablePDAMH(DefaultTableModel dtm) {
		super(dtm);
		setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		getTableHeader().setReorderingAllowed(false);
		putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
		InputMap im = getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
		KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
		im.put(enter, im.get(tab));
		KeyStroke right = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
		im.put(right, "none");
		final Action oldTabAction = getActionMap().get(im.get(tab));
		Action tabAction = new AbstractAction() {
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e) {
				oldTabAction.actionPerformed(e);
				JTable table = (JTable) e.getSource();
				int row = table.getSelectedRow();
				int originalRow = row;
				int column = table.getSelectedColumn();
				int originalColumn = column;

				while (!table.isCellEditable(row, column)) {
					oldTabAction.actionPerformed(e);
					row = table.getSelectedRow();
					column = table.getSelectedColumn();

					if (row == originalRow && column == originalColumn) {
						break;
					}
				}

			}
		};
		getActionMap().put(im.get(tab), tabAction);
	}
	
    public TableCellEditor getCellEditor(int row, int column) {
    	TableCellEditor cellEditor = mapCellEditors.get(getKey(row, column));
    	if (cellEditor != null)
    		return cellEditor;
        return super.getCellEditor(row, column);
    }

	public void setCellEditor(int i, int j, DefaultCellEditor editor) {
		if (editor != null)
			mapCellEditors.put(getKey(i, j), editor);
	}
	
	public TableCellEditor getCellEditor() {
		if (super.getCellEditor() != null)
			return super.getCellEditor();
		return new DefaultCellEditor(new JTextField());
	}

	private String getKey(int i, int j) {
		return String.valueOf(i) + "," + String.valueOf(j);
	}
}
